﻿#include <QVariant>
#include "kinputhandler.h"

InputHandler::InputHandler(QObject* parent)
    : QObject(parent)
{}


void InputHandler::attachButtons(const QList<QPushButton*>& buttons)
{
    for (auto* btn : buttons) {
        QString token = btn->property("token").toString();

        //针对 digit 和 operator 保留原有绑定
        if (token.size() == 1 && token[0].isDigit()) {
            connect(btn, &QPushButton::clicked, this, [this, token]() {
                emit digitButtonPressed(token[0]);
                });
            continue;
        }
        if (QString("+-*/").contains(token)) {
            connect(btn, &QPushButton::clicked, this, [this, token]() {
                emit operatorButtonPressed(token[0]);
                });
            continue;
        }
        if (token == "(" || token == ")") {
            connect(btn, &QPushButton::clicked, this, [this, token]() {
                emit parenthesisButtonPressed(token[0]);
                });
            continue;
        }
        if (token == ".") {
            connect(btn, &QPushButton::clicked, this, [this]() {
                emit pointButtonPressed('.');
                });
            continue;
        }

        //映射token到对应槽函数
        static const QMap<QString, std::function<void()>> actionMap = {
            { "CE",        [this]() { emit clearEntryButtonPressed(); }},
            { "C",         [this]() { emit clearButtonPressed(); }},
            { "back",      [this]() { emit backButtonPressed(); }},
            { "forward",   [this]() { emit forwardButtonPressed(); }},
            { "del",       [this]() { emit deleteButtonPressed(); }},
            { "neg",       [this]() { emit negateButtonPressed(); }},
            { "=",         [this]() { emit equalButtonPressed(); }},
            { "inv",       [this]() { emit inverseButtonPressed(); }},
            { "sqr",       [this]() { emit squareButtonPressed(); }},
            { "sqrt",      [this]() { emit sqrtButtonPressed(); }},
            { "pct",       [this]() { emit percentButtonPressed(); }}
        };

        if (actionMap.contains(token)) {
            connect(btn, &QPushButton::clicked, this, actionMap[token]);
        }
    }
}
